import { Component, OnInit } from '@angular/core';

import { SelectedCourse } from 'src/app/services/course/interfaces/selected-course.interface';
import { CourseService } from 'src/app/services/course/course.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-selected-courses',
  templateUrl: './selected-courses.component.html',
  styleUrls: ['./selected-courses.component.css']
})
export class SelectedCoursesComponent implements OnInit {
  listOfSelectedCourses: SelectedCourse[] = [];
  listOfDisplayData: SelectedCourse[] = [];
  isAllDisplayDataChecked: boolean;
  mapOfCheckedId: { [key: string]: boolean } = {};
  isIndeterminate: boolean;
  takeSourseButtonDisabled: boolean;

  constructor(
    private courseService: CourseService,
    private message: NzMessageService
  ) {}

  async ngOnInit() {
    this.listOfSelectedCourses = await this.courseService.getListOfSelectedCourses();
  }

  /**
   * 当前页面数据改变时，刷新表头复选框状态
   */
  currentPageDataChange($event: SelectedCourse[]): void {
    this.listOfDisplayData = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    // 如果所有显示的数据，都是选中的，则表头的复选框选中
    this.isAllDisplayDataChecked = this.listOfDisplayData.every(
      item => this.mapOfCheckedId[item.no]
    );
    // 如果所有显示的数据，至少有一个选中，并且不是全部选中，则表头复选框为不确定状态
    this.isIndeterminate =
      this.listOfDisplayData.some(item => this.mapOfCheckedId[item.no]) &&
      !this.isAllDisplayDataChecked;
  }

  checkAll(value: boolean): void {
    this.listOfDisplayData.forEach(
      item => (this.mapOfCheckedId[item.no] = value)
    );
    this.refreshStatus();
  }

  /**
   * 退选课程
   */
  cancelCourses() {
    this.takeSourseButtonDisabled = true;

    // 生成选中的课程数组
    const selectedCourses = [];
    for (const key in this.mapOfCheckedId) {
      if (this.mapOfCheckedId.hasOwnProperty(key)) {
        const element = this.mapOfCheckedId[key];
        if (element) {
          selectedCourses.push(key);
        }
      }
    }

    if (0 === selectedCourses.length) {
      this.takeSourseButtonDisabled = false;
      return;
    }

    this.courseService.cancelCourse(selectedCourses).subscribe(
      data => {
        this.ngOnInit();
        this.message.create('success', '退选成功！');
        this.takeSourseButtonDisabled = false;
      },
      error => {
        this.message.create('error', '退选失败！');
        this.takeSourseButtonDisabled = false;
      }
    );
  }
}
